<template>

		<div id="player" @click="lrcShow=true;">
			<div class="btn-up" ref="btn-up" @click.stop="move()"><i class="fa fa-2x fa-angle-double-up"></i></div>
			<!-- canvas 画图 -->
			<canvas id="player-canvas"></canvas>
			<!-- 播放器控件-->
			<div class="player-box absolute">
				<!-- 按钮 -->
				<div class="btns absolute hcenter">
					<el-button size="small" type="text" @click.stop='prev()'><i class="fa fa-2x fa-step-backward"></i></el-button>
					<el-button size="small" type="text" @click.stop="palyBtn()" v-show="!isplay"><i class="fa fa-2x fa-play-circle"></i></el-button>
					<el-button size="small" type="text" @click.stop="paused()" v-show="isplay"><i class="fa fa-2x fa-pause-circle"></i></el-button>
					<el-button size="small" type="text" @click.stop="next()"><i class="fa fa-2x fa-step-forward"></i></el-button>
				</div>
				<!-- 进度条 -->
				<div class="progress absolute">
					<el-slider v-model="playInfo.played" :disabled="audio.paused" :step="0.1" :format-tooltip="formatTooltip" @change="playedChange"></el-slider>
					<div class="load"></div>
				</div>
				<el-button type="text" size="small" class="list-btn absolute" @click.stop="listShow=!listShow"><i class="fa fa-2x fa-list-ul"></i></el-button>
				<div class="bottom absolute">
					<p class="musicInfo">
						{{musicLlist[indexOfList].musicName}} - {{musicLlist[indexOfList].singer}}
					</p>
					<div class="timeInfo">
						<span>{{format(Math.floor(playInfo.currentTime/60))}}:{{format( Math.round(playInfo.currentTime%60))}}/{{format(Math.floor(audio.duration/60))}}:{{format( Math.round(audio.duration%60))}}</span>
					</div>
					<div class="volume">
						<i class="fa  fa-volume-up"></i>
						<div class="volume-slider">
							<el-slider v-model="playInfo.volume" vertical @change="volumeChange" height="80px">
							</el-slider>
						</div>
					</div>
					<div class="mode">
						<div class="choose" ref='mode-choose' v-show="classFlag">
							<p @click="changeMode('radom','random')"><i class=" fa fa-random"></i><span>随机播放</span></p>
							<p @click="changeMode('line','long-arrow-right')"><i class=" fa fa-long-arrow-right"></i><span>顺序播放</span></p>
							<p @click="changeMode('one','refresh')"><i class=" fa fa-refresh"></i><span>单曲循环</span></p>
							<p @click="changeMode('loop','exchange')"><i class=" fa fa-exchange"></i><span>循环播放</span></p>
						</div>
						<i :class="playInfo.className" @click.stop="classFlag=!classFlag"></i>
					</div>
				</div>
			</div>
			<!-- 列表 -->
			<el-table class="music-list absolute" ref="music_list" :height="tableHeight" v-show="listShow" :data="musicLlist"
			 @row-click="play"
			 @click="stop(e)"
			 >
				<el-table-column type="index" label="序号" :span='4'></el-table-column>
				<el-table-column prop="musicName" label="歌名" :span='8'>
				</el-table-column>
				<el-table-column label="歌手" :span='8'>
					<template slot-scope="scope">
						<el-button type="text" class="singer-btn" @click.stop="searchBySinger(scope.row.singer)">{{ scope.row.singer }}</el-button>
					</template>

				</el-table-column>
				<el-table-column label="操作" :span='4'>
					<template slot-scope="scope">
						<el-button type="text" @click.stop="deleteOne(scope.row,scope)" :disabled="scope.$index==0&&musicLlist.length==1" size="small"><i class="fa delete fa-trash"></i></el-button>

					</template>
				</el-table-column>
			</el-table>
			<div class="lrc" v-show="lrcShow" @click.stop="classFlag=false;listShow=false; ">
				<div class="back" @click.stop="lrcShow=false"><i class="fa fa-2x fa-angle-left"></i></div>
				<div class="content">
					<div class="info">
						<p class="music-name">{{musicLlist[indexOfList].musicName}}</p>
						<p class="singer">{{musicLlist[indexOfList].singer}}</p>
					</div>
					<div class="lrcs-window">
						<ul class="lrc-list" ref="lrc-list">
							<li class="item" v-if="oLRC.al">{{oLRC.al}}</li>
							<li class="item" v-if="oLRC.ar">{{oLRC.ar}}</li>
							<li class="item" v-if="oLRC.by">{{oLRC.by}}</li>
							<li v-for="(item,index) in oLRC.ms" v-text="item.c" :value="index" :class="['item',timeFormat(playInfo.currentTime)-timeFormat(undefined== item.t?0:item.t)>=0&&timeFormat(playInfo.currentTime)<(undefined== oLRC.ms[index+1]?1:oLRC.ms[index+1].t)?'active':'']"
							 :key="index"></li>
						</ul>
					</div>
				</div>
			</div>

		</div>
</template>

<script>
	import $ from 'jquery'
	export default {
		data() {
			return {
				musicLlist:this.$store.state.muscInfo.musicLlist,
				indexOfList:this.$store.state.muscInfo.indexOfList, //当前播放索引
				tableHeight: 400,
				audio: {}, //audio对象
				canvas: {}, //canvas
				isplay: false,
				changeOrg: false,
				playInfo: {
					played: 0,
					duration: '',
					mode: 'line',
					className: 'fa fa-long-arrow-right',
					volume: 100,
					currentTime: 0
				},
				oLRC: {
					ti: "", //歌曲名
					ar: "", //演唱者
					al: "", //专辑名
					by: "", //歌词制作人
					offset: 0, //时间补偿值，单位毫秒，用于调整歌词整体位置
					ms: [] //歌词数组{t:时间,c:歌词}
				},
				classFlag: false, //选择播放模式框
				listShow: false, //列表显示标识
				playerShow: false,
				lrcShow: false,
				timer: {
					progTiemr: null,
					lrcTimer: null
				}

			}
		},
		watch:{
			'$store.state.muscInfo.indexOfList'(){
				this.play()
			}
		},
		methods: {
			play(row,col,event) {
				if ('' == this.audio.src) {
					window.audioContext.resume();
				}
				if (undefined == row || undefined == row.src) {

					this.audio.src = this.musicLlist[this.indexOfList].src;
					this.audio.play();
					this.progressManager();

				} else {
					if (row.src != this.musicLlist[this.indexOfList].src) {
						this.audio.src = row.src;
						this.musicLlist.forEach((val, index) => {
							if (this.musicLlist[index].src == row.src) {

								this.indexOfList = index;

							}
						})
						this.audio.play();
						this.progressManager(true);
					}

				}
				
				this.isplay = true;
				if(undefined !==event)
				event.cancelBubble = true;
			},
			palyBtn() {
				if ('' == this.audio.src) {
					window.audioContext.resume();
					this.play()
				} else {
					if (this.changeOrg) this.play();
					else
						this.audio.play();
					this.progressManager();
				}
				this.isplay = true;
			},
			paused() {
				this.isplay = false;
				this.changeOrg = false;
				this.audio.pause();

			},
			next() {
				this.$store.state.muscInfo.indexOfList++;
				if (this.playInfo.mode != 'random') {
					if (this.indexOfList++ < this.musicLlist.length - 1) {

						this.play();

					} else {
						if (this.playInfo.mode == 'line') {
							this.indexOfList = 0;
							this.playInfo.played = 0;
							this.isplay = false;
							this.audio.pause();
							this.changeOrg = true;

						} else {
							this.indexOfList = 0;
							this.play();
						}
					}
				} else {
					this.indexOfList = Math.floor(Math.random() * this.musicLlist.length);
					this.play();
				}


			},
			prev() {
				if (--this.indexOfList >= 0) {
					this.play();
				} else {
					this.indexOfList = 0;
					this.$message({
						message: '已经是第一首了',
						type: 'info'
					})
				}
			},
			searchBySinger(singer) { //歌手搜索
				console.log("----");
				console.log(singer);
			},
			deleteOne(row) { //列表删除
				for (let i = 0; i < this.musicLlist.length; i++) {
					if (row.id == this.musicLlist[i].id) {
						this.musicLlist.splice(i, 1);
						this.$message({
							showClose: true,
							message: "删除成功",
							type: "success"
						})
						break;
					}

				}
			},
			formatTooltip() { //格式化进度条拖动显示内容
				if (this.playInfo.played == 0)
					return 0;
				return Math.floor(this.playInfo.played / 100 * this.audio.duration / 60) + 'm' + Math.round(this.playInfo.played /
					100 * this.audio.duration % 60) + 's';
			},
			playedChange(val) {
				this.playInfo.played = val;
				this.audio.currentTime = Math.round(val / 100 * this.audio.duration);
				this.audio.play();

			},
			volumeChange(val) {
				this.playInfo.volume = val;
				this.audio.volume = this.playInfo.volume / 100;

			},
			progressManager(isNew) { //进度管理
				if (isNew == true)
					this.playInfo.played = 0;
				$(".lrc-list").css("top", 0);
				if (this.timer.progTimer == null)
					this.timer.progTimer = setInterval(() => {
						this.playInfo.currentTime = this.audio.currentTime;

						this.playInfo.played = Math.round(this.audio.currentTime / this.audio.duration * 100);
						let top = $(".lrc-list>.active")[0];
						if (undefined != top) {
							if (top.offsetTop > $(".lrcs-window").height() / 2 && top.offsetTop < $(".lrc-list").height() - $(
									".lrcs-window").height() /
								2) {
								let index = parseInt($(top).attr("value"));
								let _boolean = parseInt(this.timeFormat(this.playInfo.currentTime)) - parseInt(this.timeFormat(undefined ==
									this.oLRC.ms[index + 1] ? 0 : this.oLRC.ms[index + 1].t)) == 0;
								if (_boolean) $(".lrc-list").css("top", -(index - $(".lrcs-window").height() / 2 / 25 + 3) * 25 + 'px')
							}
						}
						if (this.audio.ended) {
							this.modeManage();
						}

					}, 300);
				this.getLrc();
			},
			modeManage() { //播放模式管理
				if (this.playInfo.mode == 'line' || this.playInfo.mode == 'loop') {
					this.indexOfList++;

					if (this.indexOfList >= this.musicLlist.length) {
						if (this.playInfo.mode == 'line') {
							this.indexOfList = 0;
							this.playInfo.played = 0;
							this.isplay = false;
							this.audio.pause();
							clearInterval(this.timer.progTimer);
							clearInterval(this.timer.lrcTimer);
							this.changeOrg = true;
							this.timer.progTimer = null;
							this.timer.lrcTimer = null;
						} else if (this.playInfo.mode == 'loop') {
							this.indexOfList = 0;
							this.audio.play();
							this.progressManager();
						}

					} else {
						this.play();
					}

				} else if (this.playInfo.mode == 'random') {
					this.indexOfList = Math.round(Math.random() * this.musicLlist.length - 1);
					this.play();
				} else if (this.playInfo.mode == 'one') {
					this.audio.currentTime = 0;
					this.play();
				}
			},
			format(val) {
				//格式化歌曲时间
				if (isNaN(val))
					return '00';
				else {
					if (val < 10) {
						return '0' + val;
					} else {
						return val;
					}
				}

			},
			changeMode(mode, _class) {
				//播放模式切换
				if (mode != this.playInfo.mode) {
					this.playInfo.mode = mode;
					this.playInfo.className = "fa fa-" + _class;
					this.classFlag = false;
				}
			},
			move() {
				this.playerShow = !this.playerShow;
				if (this.playerShow) {
					this.$refs["btn-up"].style.transform = "rotateZ(0deg)";
					$("#player").stop().animate({
						bottom: "-65px"
					}, 1000);
				} else {
					this.$refs["btn-up"].style.transform = "rotateZ(180deg)";
					$("#player").stop().animate({
						bottom: 0
					}, 1000)
				}
			},
			getLrc() {
				this.$axios({
					url: this.musicLlist[this.indexOfList].lrc,
					type: 'get'
				}).then(res => {
					this.createLrcObj(res.data);
				})
			},
			createLrcObj(lrc) { //歌词处理
				this.oLRC = {
					ti: "", //歌曲名
					ar: "", //演唱者
					al: "", //专辑名
					by: "", //歌词制作人
					offset: 0, //时间补偿值，单位毫秒，用于调整歌词整体位置
					ms: [] //歌词数组{t:时间,c:歌词}
				}
				if (lrc.length == 0) return;
				var lrcs = lrc.split('\n'); //用回车拆分成数组
				for (var i in lrcs) { //遍历歌词数组
					lrcs[i] = lrcs[i].replace(/(^\s*)|(\s*$)/g, ""); //去除前后空格
					var t = lrcs[i].substring(lrcs[i].indexOf("[") + 1, lrcs[i].indexOf("]")); //取[]间的内容
					var s = t.split(":"); //分离:前后文字
					if (isNaN(parseInt(s[0]))) { //不是数值
						for (var i in this.oLRC) {
							if (i != "ms" && i == s[0].toLowerCase()) {
								this.oLRC[i] = s[1];
							}
						}
					} else { //是数值
						var arr = lrcs[i].match(/\[(\d+:.+?)\]/g); //提取时间字段，可能有多个
						var start = 0;
						for (var k in arr) {
							start += arr[k].length; //计算歌词位置
						}
						var content = lrcs[i].substring(start); //获取歌词内容
						for (var k in arr) {
							var t = arr[k].substring(1, arr[k].length - 1); //取[]间的内容
							var s = t.split(":"); //分离:前后文字
							this.oLRC.ms.push({ //对象{t:时间,c:歌词}加入ms数组
								t: (parseFloat(s[0]) * 60 + parseFloat(s[1])).toFixed(3),
								c: content
							});
						}
					}
				}
				this.oLRC.ms.sort(function(a, b) { //按时间顺序排序
					return a.t - b.t;
				});
			},
			timeFormat(val) {
				var re = /([0-9]+\.[0-9]{2})[0-9]*/;
				return parseFloat((val + '').replace(re, "$1"));
			}
		},
		mounted() {
			// this.getLrc();
			this.audio = new Audio();
			let $player = $("#player");
			console.log("audio create");
			this.canvas = $("#player-canvas");
			let _this = this;
			this.audio.crossOrigin = "anonymous";
			this.canvas[0].width = window.innerWidth;
			this.canvas[0].height = $player.height();
			$("#player>.lrc").height(window.innerHeight - $("#player").height() + 'px');

			function drow() {
				var can = $("#player-canvas")[0];
				window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
				window.audioContext = new AudioContext();
				var analyser = audioContext.createAnalyser();
				var source = audioContext.createMediaElementSource(_this.audio);
				source.connect(analyser);
				analyser.connect(audioContext.destination);
				var arr = new Uint8Array(analyser.frequencyBinCount);
				var ctx = can.getContext("2d");
				var color = ctx.createLinearGradient(100, 0, 100, $(can).height());
				color.addColorStop(0, "#d3959b");
				color.addColorStop(0.5, "pink");
				color.addColorStop(1, "#bfe6ba");
				ctx.fillStyle = color;

				function dr() {
					requestAnimationFrame(dr)
					analyser.getByteFrequencyData(arr);

					ctx.clearRect(0, 0, can.width, can.height);
					for (var i = 0; i < 1000; i++) {

						ctx.fillRect(i, $(can).height(), 2, -arr[i] * 0.32);
					}
				}
				dr();

			}

			drow();
			//歌曲进度条初始化
			$(".el-slider__bar").css("background",
				"linear-gradient(45deg,rgba(254,172,94,0.8),rgba(199,121,208,0.8),rgba(75,192,200,0.8))");
			window.onresize = function() {
				_this.canvas.width(window.innerWidth)
				_this.canvas.height($player.height());
				$("#player>.lrc").height(window.innerHeight - $("#player").height() + 'px');
				if ($(window).width() <= 750) { //手机屏幕
					_this.tableHeight = 600;
					$(".music-list").css({
						width: '100%',
					})
				} else {
					$(".music-list").css({
						width: '40%'
					})
					_this.tableHeight = 400;
				}
			}
			//点击其他地方关闭音乐列表和模式列表
			document.addEventListener('click', e => {
				if (!this.$refs.music_list.$el.contains(e.target) && e.target.id != 'music_list') {
					this.listShow = false;
				}
				if (!this.$refs['mode-choose'].contains(e.target) && e.target.id != 'mode-choose') {
					this.classFlag = false;
				}
			})

		}
	}
</script>

<style scoped lang="less">
	.absolute {
		position: absolute;
	}

	.hcenter {
		top: 50%;
		transform: translateY(-50%);
	}

	@height: 65px;

	.wh100 {
		width: 100%;
		height: 100%;
	}

	#player {
		position: fixed;
		z-index: 1000;
		width: 100%;
		height: @height;
		background-color: white;
		cursor: pointer;
		bottom: 0;
		left: 0;

		#player-canvas {
			.absolute();
			display: block;
			// background: linear-gradient(#D9ECFF, #F2F6FC, #ECF5FF, #B3D8FF, #C6E2FF);
		}

		.btn-up {
			.absolute();
			cursor: pointer;
			transform: rotateZ(180deg);

			&:hover {
				color: #00BFFF;
			}

			right: 10px;
			top: -50px;
		}

		.music-list {
			width: 300px;
			right: 0;
			width: 40%;
			max-height: 500px;

			@media screen and (max-width: 760px) {
				width: 100%;
			}

			bottom:100%;

			text-align:center;

			* {
				text-overflow: ellipsis;
			}


			.delete {
				font-size: 16px;

			}

			.singer-btn {
				max-width: 220px !important;

				span {
					display: block !important;
					width: 100% !important;
					color: red;
					text-overflow: ellipsis;
				}
			}

		}

		//播放器控件
		.player-box {
			width: 100%;
			height: 100%;

			.btns {
				height: 44px;
				padding-left: 10px;
				width: 100px;
				display: flex;
				justify-content: space-around;

			}

			;

			.progress {
				width: 65%;
				height: 4px;

				left: 50%;

				transform: translateX(-50%);

				&>.el-slider {
					// position: absolute;
					opacity: .8;
					margin-top: -1%;
					height: 10px !important;

					&>.el-slider__runway {
						height: 100% !important;

						&>.el-slider__button-wrapper {
							width: 20px !important;
							height: 20px !important;

							&>.el-slider__button {
								width: 9px !important;
								height: 9px !important;
							}
						}
					}
				}

				&>.load {
					height: 6px;
					width: 10%;
					border-radius: 3px;
					background-color: #BCBEC2;
					margin-top: 6px;
				}


			}

			&>.list-btn {
				right: 6%;
				top: 2px;
			}

			&>.bottom {
				width: 70%;
				bottom: 8px;
				left: 18%;
				display: flex;
				justify-content: space-between;

				.musicInfo {
					max-width: 150px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;

					&:hover {
						overflow: initial;
						text-overflow: initial;
					}
				}

				.volume {
					position: relative;
					cursor: pointer;

					.volume-slider {
						position: absolute;
						display: none;
						z-index: 999;
						bottom: 3px;
						left: 1px;
					}

					&:hover {
						.volume-slider {
							display: block;
						}
					}

					&>.fa {
						position: absolute;

						bottom: 0;

					}
				}

				.mode {
					position: relative;

					.choose {
						position: absolute;
						z-index: 999;
						width: 100px;
						height: 100px;
						border: 1px solid #00BFFF;
						border-radius: 3px;
						text-align: center;
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						background: linear-gradient(to right, #d3959b, #bfe6ba);
						top: -120px;
						left: -50px;

						&>p {
							cursor: pointer;
							text-overflow: ellipsis;

							&:hover {
								color: deepskyblue;
							}

							span {
								padding-left: 5px;
							}
						}

					}

					.fa {
						cursor: pointer;

						&:hover {
							color: deepskyblue;
						}
					}
				}
			}
		}

		.lrc {
			position: absolute;
			cursor:default;
			z-index: 999;
			width: 100%;
			bottom: 100%;
			background: #DCDFE6;

			.back {
				position: absolute;
				left: 10px;
				cursor: pointer;

				&:hover {
					color: #00BFFF;
				}
			}

			.content {
				height: 100%;
				display: flex;
				flex-direction: column;

				.info {
					height: auto;

					.singer {
						font-size: .8em;
					}
				}

				.lrcs-window {
					flex: 1;
					overflow: hidden;
					position: relative;

					.lrc-list {
						position: absolute;
						width: 100%;
						list-style: none;
						top: 0;

						.item {
							height: 1.5625rem;
							line-height: 1.5625rem;
						}

						.active {
							color: #00BFFF;

							&+.active {
								color: #2c3e50;
							}

							// &+li{
							// 	color: #2c3e50;
							// }
						}
					}
				}
			}
		}

		/*
		  #player
		 */
		@media screen and(max-width: 750px) {
			height: 75px;

			&>.player-box {
				.progress {
					width: 80%;
				}

				.list-btn {
					top: 11px;
				}

				.btns {
					left: 38%;
				}

				&>.bottom {
					width: 80%;
					left: 8%;
					bottom: 1px;
				}
			}

		}

		.close {
			animation: close 1s;
		}

		@keyfarmes close {
			0% {
				opacity: 1;
				width: 100%;
				height: 100%;
			}

			100% {
				opacity: 0;
				width: 0%;
				height: 0%;
			}
		}
	}
</style>
